VSCode Debug小记

前言

VSCode内置Node.js运行时,可以直接debug JavaScript, TypeScript。 通过快捷键F5启动debug(初次使用时会自动生成.vscode/launch.json配置文件)。其它语言的debug,则需要安装相应的debuggers extensions

Launch配置

  • Node debug支持两种mode, launch和attach.

    1
    2
    3
    {
    "request": "launch" // "attach"
    }
  • 支持全局launch.可以在user settings中通过launch属性,设置全局launch. 当workspace存在launch.json文件是,会覆盖全局设置.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    "launch": {
    "version": "0.2.0",
    "configurations": [{
    "type": "node",
    "request": "launch",
    "name": "Launch Program",
    "program": "${file}"
    }]
    }

Breakpoints断点

VSCode支持expression condition,hit count, column, function, 以及普通断点

  • expression condition: 当expression为true时,触发断点.
  • hit count: 命中多少次之后触发断点
  • column: 执行到这列的时候触发断点。debug 压缩过的单行代码时非常有用。快捷键shift + F9
  • function: 代替在源码中直接设置断点,可以直接通过设置一个函数名来定义一个断点。当函数源码不可见,而函数名已知时非常有用。在BREAKPOINTS header 中点击+,输入函数名

Debug ES6+

有一些还不支持的Node.js特性,不能直接debug, 需要先用babel转换并且通过source-maps进行映射,来进行debug

1
2
3
4
5
6
7
//package.json
// 添加npm script
{
"scripts": {
"debug": "babel src --out-dir debug --source-maps"
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// .vscode/tasks.json
// 添加VSCode task
{
{
"version": "0.1.0",
"command": "npm",
"isShellCommand": true,
"showOutput": "always",
"suppressTaskName": true,
"tasks": [
{
"taskName": "debug",
"args": ["run", "debug"]
}
]
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "启动程序",
"program": "${workspaceRoot}/src/main.js",
"cwd": "${workspaceRoot}",
"sourceMaps": true,
"outFiles": [
"${workspaceRoot}/debug/main.js"
],
"preLaunchTask": "debug"
}
]
}